#!/usr/bin/env bash

if [[ $WORK_DIR == '' ]]; then
  REALPATH=$(realpath $0)
  WORK_DIR=$(cd $(dirname $REALPATH) && pwd)
fi
echo "Upgrade srs-cloud at $WORK_DIR from $0"

if [[ $TARGET_VERSION == '' ]]; then
  TARGET_VERSION=$1
fi
TAG_NAME=$(echo $TARGET_VERSION|grep '^v')
echo "The TARGET_VERSION=$TARGET_VERSION TAG_NAME=$TAG_NAME"

if [[ $TARGET_VERSION == '' && $TAG_NAME == '' ]]; then
  echo "Usage: $0 <branch|tag>"
  echo "    branch|tag    The branch or tag to upgrade to."
  echo "For example:"
  echo "    $0 lighthouse"
  echo "    $0 v1.2.3"
  echo "Remark:"
  echo "    You will lost local changes by git checkout"
  exit 1
fi

cd $WORK_DIR && git remote -v && git branch -vva
if [[ $? -ne 0 ]]; then echo "Prepare upgrade failed"; exit 1; fi

if [[ ! -d /usr/local/srs-cloud && $(uname -s) == 'Darwin' ]]; then
  echo "Directly finish upgrade for macOS development"
  sleep 30; exit 0;
fi

# Get the metadata of machine.
if [[ -f .env ]]; then source .env; fi
echo "LoadEnv CLOUD=$CLOUD REGION=$REGION, SOURCE=$SOURCE"

# Initialize the REGION and SOURCE.
bash auto/upgrade_region $SOURCE

# Try git stash first, ignore any error.
git stash 2>>upgrade.error.log
if [[ $? -ne 0 ]]; then
  echo "Warning: git stash failed, see upgrade.error.log for detail\n";
fi

echo "Reset code files at parent directory"
git checkout ../ && git fetch --all
if [[ $? -ne 0 ]]; then echo "Reset code files failed"; exit 1; fi

echo "Create target branch"
CURRENT_BRANCH=$(git branch |grep '*' |awk '{print $2}')
if [[ $CURRENT_BRANCH != $TARGET_VERSION ]]; then
  EXISTS_BRANCH=$(git branch --list $TARGET_VERSION |awk '{print $1}')
  if [[ $EXISTS_BRANCH == $TARGET_VERSION ]]; then
    echo "Checkout to $TARGET_VERSION for current is $CURRENT_BRANCH"
    git checkout $TARGET_VERSION
  else
    echo "Checkout new $TARGET_VERSION for current is $CURRENT_BRANCH"
    if [[ $TAG_NAME != '' ]]; then
      git checkout -b $TARGET_VERSION $TARGET_VERSION
    else
      git checkout -b $TARGET_VERSION origin/$TARGET_VERSION
    fi
  fi
else
  echo "Already on branch $TARGET_VERSION"
fi
if [[ $? -ne 0 ]]; then echo "Create branch $TARGET_VERSION codes failed"; exit 1; fi

echo "Update branch $TARGET_VERSION"
if [[ $(git tag -l $TARGET_VERSION) == '' ]]; then
  echo "Pull for branch $TARGET_VERSION"
  git pull
fi
if [[ $? -ne 0 ]]; then echo "Upgrade codes failed"; exit 1; fi

# Got the latest script and upgrade.
# Remark: Never change the scripts path of upgrade_living here, because both old and new code depends on it.
echo "Start living upgrade" && bash upgrade_living $REGION
if [[ $? -ne 0 ]]; then echo "Living upgrade failed"; exit 1; fi

echo "Upgrade OK"
